#!/usr/bin/perl

@files = (ls("perl*/*.patch"), ls("cperl*/*.patch"));

print "#!/bin/sh\n\n";

%map = ( );

foreach(@files) {
	$hash = `sha1sum $_`;
	$hash =~ s/\s.*//s;

	if(!defined($map{$hash})) {
		$map{$hash} = $_;
		deref($_) if -l $_;
	} elsif(-l $_) {
		$old = inode($map{$hash});
		$new = inode($_);
		lnsf($map{$hash}, $_) unless $old eq $new;
	} else {
		lnsf($map{$hash}, $_);
	}
}

# Version-aware glob; sorts 5.27.10 after 5.27.9

sub ls {
	return sort {
		my @a = split /\./, $a;
		my @b = split /\./, $b;
		while(@a && @b) {
			my $ai = shift @a;
			my $bi = shift @b;
			my $r = $ai <=> $bi;
			return $r if $r;
		}
		return 1 if @a;
		return -1 if $b;
		return 0;
	} glob(shift);
}

sub lnsf
{
	my ($orig,$link) = @_;
	print "ln -sf ../$orig $link\n";
}

sub deref
{
	my $name = shift;
	print "cp $name $name.tmp && rm $name && mv $name.tmp $name\n";
}

sub inode
{
	my $name = shift;
	my @stat = stat $name or die "stat $name: $!";
	return @stat[0].':'.@stat[1];
}
